#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project: Jmpy
@File   : testWK811.py
@Author : Link
@Date   : 2025/5/1 12:01
@Remark :

"""
import os.path
import unittest

import pandas as pd

from jslBaseInterface.jmp_box import JmpyBox
from jslBaseInterface.jmp_file import JmpyFile
from jslBasePlot.jmp_plot_clustering import JmpyPlotClustering


class MyTestCaseWk811(unittest.TestCase):

    def setUp(self) -> None:
        """

        """
        print("Setup调用")
        self.path = r"Wk811Data\WK_TY_0.csv"

    def testPandasCheckRdWk811(self):
        """
        数据列中的FAIL_FLAG, 表示的空坐标, Wafer外部未测区域
        <class 'pandas.core.frame.DataFrame'>
        RangeIndex: 2871050 entries, 0 to 2871049
        Data columns (total 10 columns):
         #   Column          Dtype
        ---  ------          -----
         0   Unnamed: 0      int64
         1   Type            object
         2   dieSize         float64
         3   failureType     object
         4   lotName         object
         5   trainTestLabel  object
         6   waferIndex      float64
         7   X_COORD         int64
         8   Y_COORD         int64
         9   FAIL_FLAG       int64
        dtypes: float64(2), int64(4), object(4)
        memory usage: 219.0+ MB

        ['[0 0]' 'Near-full' 'none' 'Random' 'Edge-Loc' 'Loc' 'Edge-Ring'
         'Scratch' 'Center' 'Donut']
        :return:
        """
        df: pd.DataFrame = pd.read_csv(self.path)
        assert df is not None
        print(df.info())
        print(df.iloc[0])
        print(df["failureType"].unique())
        print(df["trainTestLabel"].unique())

    def testJmpRdCsvDoClu(self):
        """
        None
        Unnamed: 0               0
        Type               WK_TY_0
        dieSize              512.0
        failureType          [0 0]
        lotName           lot14177
        trainTestLabel       [0 0]
        waferIndex             1.0
        X_COORD                  0
        Y_COORD                  0
        FAIL_FLAG                0
        Name: 0, dtype: object

        FAIL_FLAG = 2为FAIL
        FAIL_FLAG = 1为PASS
        FAIL_FLAG = 0为外部区域
        TODO:
            1. 将FAIL_FLAG的数据删除
            2. 将 FAIL_FLAG = 1的值设置为0
            3. 将 FAIL_FLAG = 2的值设置可以保存原来的值
            4. 调用JMP的聚类分析
        :return:
        """
        print("数据处理")
        script_csv_path = r"Wk811Data\WK_TY_0_J.csv"
        df: pd.DataFrame = pd.read_csv(self.path)
        assert df is not None
        df = df.replace({'FAIL_FLAG': {1: 0, 2: 1}})
        df.to_csv(script_csv_path)

        print("Jmp操作执行")
        scripts = [
            JmpyFile.jCloseAll(),
            JmpyFile.jLoadCsv(script_csv_path, in_vis=True),  # 加载CSV
            JmpyPlotClustering.jWaferClustering(
                "X_COORD", "Y_COORD", "FAIL_FLAG", "lotName", "waferIndex")
        ]
        JmpyFile.jExecuteScript(
            *scripts
        )

    def testJmpRdCsvDoMultiClu(self):
        """
        处理多份数据
        然后用多个Box来放置数据
        TODO: 操作流程
            0. Python将数据清洗后保存为csv
            1. JSL LoadCsv数据, 并给每个数据设置一个dt名字
            2. 配置列格式, 看情况, 也许不需要
            3. 绘制需要的图像, 给每个图像设置一个plot名字
            
        :return:
        """
        path_list = [
            {"path": r"Wk811Data\WK_TY_0.csv", "jmp": r"Wk811Data\WK_TY_0_J.csv", "dt": "dt_0", "plot": "plot_0", },
            {"path": r"Wk811Data\WK_TY_1.csv", "jmp": r"Wk811Data\WK_TY_1_J.csv", "dt": "dt_1", "plot": "plot_1", },
            {"path": r"Wk811Data\WK_TY_2.csv", "jmp": r"Wk811Data\WK_TY_2_J.csv", "dt": "dt_2", "plot": "plot_2", },
            # {"path": r"Wk811Data\WK_TY_3.csv", "jmp": r"Wk811Data\WK_TY_3_J.csv", "dt": "dt_3", "plot": "plot_3", },
            # {"path": r"Wk811Data\WK_TY_4.csv", "jmp": r"Wk811Data\WK_TY_4_J.csv", "dt": "dt_4", "plot": "plot_4", },
            # {"path": r"Wk811Data\WK_TY_5.csv", "jmp": r"Wk811Data\WK_TY_5_J.csv", "dt": "dt_5", "plot": "plot_5", },
        ]

        for each in path_list:
            df: pd.DataFrame = pd.read_csv(each["path"])
            assert df is not None
            df = df.replace({'FAIL_FLAG': {1: 0, 2: 1}})
            df.to_csv(each["jmp"])

        scripts = [JmpyFile.jCloseAll()]
        # 读取文件
        for each in path_list:
            scripts.append(JmpyFile.jLoadCsv(each["jmp"], dt_name=each["dt"]))
        # 指定dt数据绘制Plot并指向到变量名pt
        pts = []
        for each in path_list:
            name, suffix = os.path.splitext(os.path.split(each["jmp"])[-1])
            plot = JmpyPlotClustering.jWaferClustering(
                "X_COORD", "Y_COORD", "FAIL_FLAG", "lotName", "waferIndex",
                title=each["path"]
            )
            post_plot = JmpyPlotClustering.jWaferCluster(
                name, r"Wk811Data\{}_Cluster.csv".format(name), "lotName", "waferIndex"
            )
            plot = JmpyBox.jPlatForm([plot, post_plot], dt=each["dt"], pt=each["plot"])
            scripts.append(plot)
            pts.append(each["plot"])

        biv = "win1"
        scripts += [
            JmpyBox.jNewWin(
                JmpyBox.jGroupBox(*pts),
                title="聚类分析报告", rbiv=biv
            ),
            # JmpFile.jSaveInteractiveHtml(r"D:\\testJmpRdCsvDoMultiCluGenHtml.html", "win1"),
            # JmpFile.jCloseAll(),
        ]
        JmpyFile.jPrintScript(*scripts)
        JmpyFile.jExecuteScript(*scripts)
